package com.daxia.ogmall.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;

import com.daxia.ogmall.common.ProfitType;
import com.daxia.ogmall.daobase.GenericDAOHibernate;
import com.daxia.ogmall.dto.ProfitDTO;
import com.daxia.ogmall.model.Profit;
import com.daxia.ogmall.support.Page;
import com.daxia.ogmall.util.DateUtils;

@Repository
public class ProfitDAO extends GenericDAOHibernate<Profit> {

    public List<Profit> find(ProfitDTO dto, Page page) {
        StringBuilder hql = new StringBuilder();
        List<Object> paras = new ArrayList<Object>();
        hql.append("From Profit n where 1 = 1 ");
        if (dto.getId() != null) {
            hql.append(" and n.id = ? ");
            paras.add(dto.getId());
        }
        if (dto.getUser() != null) {
        	if (dto.getUser().getId() != null) {
	            hql.append(" and n.user.id = ? ");
	            paras.add(dto.getUser().getId());
        	}
        }			
        if (dto.getSubAccountUserId() != null) {
        	if (dto.getSubAccountUserId().getId() != null) {
        		hql.append(" and n.subAccountUserId.id = ? ");
        		paras.add(dto.getSubAccountUserId().getId());
        	}
        }
        if (dto.getType() != null) {
            hql.append(" and n.type = ? ");
            paras.add(dto.getType());
        }
        hql.append(" order by n.id desc ");
        return super.find(hql.toString(), paras.toArray(), page);
    }
    
    public Profit findOne(ProfitDTO dto) {
		Page page = new Page();
		page.setPageSize(1);
		page.setPage(1);
		
		List<Profit> list = this.find(dto, page);
	    return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

	public double totalProfitByTypeAndUser(ProfitType type, Long userId, Date start, Date end) {
		String hql = "select sum(amount) from Profit where type = ? and user.id = ? ";
		List<Object> paras = new ArrayList<Object>();
		paras.add(type.getValue());
		paras.add(userId);
		if (start != null) {
			hql += " and time >= ? ";
			paras.add(DateUtils.getBeginningOfADay(start));
		}
		if (end != null) {
			hql += " and time <= ? ";
			paras.add(DateUtils.getEndOfADay(end));
		}
		return super.sumByHql(hql, paras.toArray());
	}
}
